<template>
  <el-dialog
    title="分配到权限"
    :visible.sync="dialogVisible"
    :before-close="cancel"
    :close-on-click-modal="false"
    class="vc-dialog-form dialog-assign-perms"
    width="400px">
    <div class="vc-page-parts">
      <div class="part-left" style="width: 100% !important">
        <el-tree
          ref="assignTree"
          class="org-tree"
          node-key="id"
          highlight-current
          :empty-text="treeEmptyText"
          :data="treeData"
          :props="defaultProps"
          :default-expanded-keys="expandedKeys"
          :expand-on-click-node="false"
          @node-click="handleNodeClick">
          <span class="slot-tree" slot-scope="{ node }">
            <i class="vc-icon" :class="node.data.type == 'mgroup' ? 'vc-icon-tree-module' : 'vc-icon-tree-perm'"></i>
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>

      <!-- <div class="right">
        <el-form ref="assignForm" :model="assignForm" :rules="rules" label-width="95px" size="small">
          <el-form-item label="操作名称" prop="name">
            <el-input v-model="assignForm.name" maxlength="20" placeholder="请输入" clearable @clear="$refs.assignForm.validateField('name')"></el-input>
          </el-form-item>

          <el-form-item label="操作描述" prop="descr">
            <el-input v-model="assignForm.descr" maxlength="100" placeholder="请输入" clearable type="textarea" :rows="4"
                      @clear="$refs.assignForm.validateField('descr')"></el-input>
          </el-form-item>
        </el-form>
      </div> -->
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button type="primary" size="small" :disabled="disabled" @click="sure">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { validateInput } from '@/utils/validator'

export default {
  name: 'assignPerms',
  props: ['dialogVisible', 'id', 'resourceType'],
  data () {
    return {
      treeData: [],
      expandedKeys: [],
      treeEmptyText: '',
      defaultProps: {
        id: 'id',
        label: 'text',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      assignForm: {
        // name: '',
        // descr: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入操作名称', trigger: 'blur' },
          { validator: validateInput, trigger: 'blur' }
        ],
        descr: [
          { validator: validateInput, trigger: 'blur' }
        ]
      },
      disabled: false
    }
  },
  watch: {
    dialogVisible (val) {
      if (!val) return
      this.disabled = false
      this.findInfoByResourceIdAndType(this.id)
    }
  },
  methods: {
    /**
     * 通过ID获取该菜单对应的所有权限
     */
    findInfoByResourceIdAndType (id) {
      this.$api.findInfoByResourceIdAndType({
        data: {
          resourceId: id,
          type: this.resourceType
        }
      }).then(res => {
        if (!res.success || !res.data) {
          this.assignForm = this.GLOBAL.object.clearValOfObj(this.assignForm)
        } else {
          this.assignForm = res.data
        }
        this.getMGroupTreeCurr(this.assignForm.permissionId || '')
        this.$nextTick(() => { this.$refs.assignForm && this.$refs.assignForm.clearValidate() })
      })
    },
    /**
     * 获取左侧模块组树数据
     */
    getMGroupTreeCurr (checkedKey) {
      this.$api.getMGroupTreeCurr().then(res => {
        if (!res.success || !res.data || !res.data.length) {
          this.treeData = []
          this.treeEmptyText = this.GLOBAL.QUERY.EMPTY_TEXT
          return
        }
        this.treeData = this.GLOBAL.array.transToTreeData(res.data)
        let checked = checkedKey ? res.data.filter(item => item.id == checkedKey) : []
        if (!checked.length) {
          this.expandedKeys = []
          this.treeData.forEach(item => { this.expandedKeys.push(item.id) })
          this.$nextTick(() => { this.$refs.assignTree && this.$refs.assignTree.setCurrentKey(null) })
          return
        }
        this.expandedKeys = []
        this.expandedKeys.push(checked[0].pid)
        this.$nextTick(() => { this.$refs.assignTree && this.$refs.assignTree.setCurrentKey(checkedKey) })
      })
    },
    /**
     * 树节点被点击时的回调
     */
    handleNodeClick (data) {
      if (!this.$refs.assignTree) {
        return
      }
      if (data.type != 'permission') {
        this.$nextTick(() => {
          this.$refs.assignTree.setCurrentKey(this.assignForm.permissionId || null)
        })
        return
      }
      this.assignForm.permissionId = data.id
      this.$nextTick(() => { this.$refs.assignTree.setCurrentKey(data.id) })
    },
    /**
     * 分配到权限
     */
    sure () {
      if (this.disabled) {
        return
      }
      if (!this.assignForm.permissionId) {
        this.$notifyBox('请选择权限')
        return
      }
      // this.$refs.assignForm.validate((valid) => {
      //   if (!valid) {
      //     return false;
      //   }
      let data = Object.assign(this.assignForm, {
        resourceId: this.id,
        resourceType: this.resourceType
      })
      this.disabled = true
      let api = !this.assignForm.id ? 'addResourceOperation' : 'modifyResourceOperation'
      this.$api[api]({
        data: data
      }).then(res => {
        this.callBack(res)
      }).catch(() => {
        this.disabled = false
      })
      // });
    },
    callBack (res) {
      if (!res.success) {
        this.disabled = false
        return
      }
      this.$emit('close', res.data || {})
      this.$notifyBox('操作成功', 'success')
    },
    /**
     * 取消
     */
    cancel () {
      this.$emit('close', false)
    }
  }
}
</script>

<style lang="less">
.dialog-assign-perms {
  .el-dialog__body {
    padding: 0 !important;
  }
  .vc-page-parts {
    height: 300px !important;
    .part-left {
      width: calc(40% - 1px) !important;
      margin-right: 0 !important;
      border: none !important;
      border-right: 1px solid #DFE5EE !important;
      border-radius: 0 !important;
      .org-tree {
        height: 100% !important;
      }
    }
    .right {
      width: 60%;
      padding: 20px 0 0;
    }
  }
}
</style>
